
#include "StdAfx.h"
#include "GYDataSet.h"
#include "CommonFun.h"
#include "CommonDef.h"
#include <xstring>

CDatabase CGYDataSet::m_db;

CGYDataSet::CGYDataSet()
{
	m_rcLastError	= 0;

	if(!m_db.IsOpen())
		ConnectDatabase();
}

CGYDataSet::CGYDataSet(CString strSQL)
{
	if(!m_db.IsOpen())
		ConnectDatabase();

	if(m_db.IsOpen())
		OpenTable(strSQL);
}

CGYDataSet::~CGYDataSet()
{
	if(IsOpen())
		Close();
}

BOOL CGYDataSet::OpenTable(CString strSQL)
{
	BOOL bRet = TRUE;
	m_pDatabase = &m_db;

	try
	{
		if(IsOpen())
			Close();

		Open(CRecordset::snapshot , strSQL, CRecordset::readOnly);
	}
	catch(CDBException* e)
	{
		m_strLastError = e->m_strError;
		m_rcLastError = e->m_nRetCode;

		bRet = FALSE;
	}
	catch(...)
	{
		bRet = FALSE;
	}

	return bRet;
}

BOOL CGYDataSet::ExecuteSQL(CString strSQL)
{
	BOOL bRet = TRUE;
	try
	{
		m_db.ExecuteSQL(strSQL);
	}
	catch(CDBException* e)
	{
		m_strLastError = e->m_strError;
		m_rcLastError = e->m_nRetCode;

		bRet = FALSE;
	}
	catch(...)
	{
		bRet = FALSE;
	}

	return bRet;
}


BOOL CGYDataSet::ConnectDatabase()
{
	CString strIniFile = GetExePath();
	strIniFile += _T("\\");
	strIniFile += GYWA_INI_FILE;
	
	CString strConnectStr;
	CString strPropName;
	CString strPropValue;
	
	TCHAR szName[MAX_PATH] = {0};
	TCHAR szValue[MAX_PATH] = {0};
	
	int nPropNun = ::GetPrivateProfileInt(_T("Connect"), _T("PropertyNumber"), 0, strIniFile);
	for(int i = 0; i < nPropNun; i++)
	{
		strPropName.Format(_T("PropertyName%02d"), i);
		strPropValue.Format(_T("PropertyValue%02d"), i);
		
		::GetPrivateProfileString(_T("Connect"), strPropName, _T(""), szName, MAX_PATH, strIniFile);
		::GetPrivateProfileString(_T("Connect"), strPropValue, _T(""), szValue, MAX_PATH, strIniFile);

		//  Password is encrypted, it need to be decrypted.
		if(_tcsicmp(szName, _T("PWD")) == 0)
		{
			CString strDecryptedPwd = DecryptString(szValue);
			_tcscpy(szValue, strDecryptedPwd);
		}
		
		strConnectStr += szName;
		strConnectStr += _T("=");
		strConnectStr += szValue;
		strConnectStr += _T(";");
	}
	
	try
	{
		m_db.OpenEx(strConnectStr, CDatabase::noOdbcDialog);
	}
	catch(CDBException* e)
	{
		CString strErrorInfo = _T("Connect Error:\r\n") + e->m_strError;

#ifdef _DEBUG
		strErrorInfo += _T("\r\nConnect string:\r\n") + strConnectStr;
#endif

		::MessageBox(NULL, strErrorInfo, _T("Connect Error"), MB_OK|MB_ICONSTOP);
		return FALSE;
	}
	catch(...)
	{
		ASSERT(FALSE);
		return FALSE;
	}
	
	return TRUE;
}

BOOL CGYDataSet::BeginTrans()
{
	return m_db.BeginTrans();
}

BOOL CGYDataSet::CommitTrans()
{
	return m_db.CommitTrans();
}

BOOL CGYDataSet::Rollback()
{
	return m_db.Rollback();
}
